<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div id="app">
      <button @click="active = 'Home'">首页</button>
      <button @click="active = 'Classify'">分类页</button>
      <button @click="active = 'Cart'">购物车</button>
      <button @click="active = 'Mine'">我的</button>

      <hr />

      <!-- <home v-if="active === 1"></home>
      <classify v-if="active === 2"></classify>
      <cart v-if="active === 3"></cart>
      <mine v-if="active === 4"></mine> -->

      <!-- component叫做动态组件 -->
      <!-- 配合is属性, is里面是组件注册的名字的字符串 -->

      <!-- 动态组件在切换的过程中，组件会自动地创建和销毁 -->
      <!-- keep-alive表示缓存组件，可以让组件在切换地过程中不会销毁和重新创建 -->
      <keep-alive>
        <component :is="active"></component>
      </keep-alive>
    </div>

    <script src="./vue.js"></script>
    <script>
      const Home = {
        template: `
          <div>这是主页面</div>
        `,
        mounted() {
          console.log("主页面被加载了");
        },
        beforeUnmount() {
          console.log("主页面被销毁了");
        },
      };

      let timer;
      const Classify = {
        data() {
          return {
            count: 1,
          };
        },
        template: `
          <div>这是分类页面 - {{ count }} - <button @click="count++">count++</button></div>
        `,
        mounted() {
          console.log("分类页面被加载了");
          // setInterval(() => {
          //   this.count++;
          // }, 1000);
        },
        beforeUnmount() {
          console.log("分类页面被销毁了");
        },
        // 若组件实例是 <KeepAlive> 缓存树的一部分，当组件被插入到 DOM 中时调用。
        activated() {
          console.log("分页回来了");
          timer = setInterval(() => {
            this.count++;
          }, 1000);
        },
        // 若组件实例是 <KeepAlive> 缓存树的一部分，当组件从 DOM 中被移除时调用。
        deactivated() {
          console.log("分页离开了了");
          clearInterval(timer);
        },
      };

      const Cart = {
        template: `
          <div>这是购物车页面</div>
        `,
        mounted() {
          console.log("购物车页面被加载了");
        },
        beforeUnmount() {
          console.log("购物车页面被销毁了");
        },
      };

      const Mine = {
        template: `
          <div>这是我的页面</div>
        `,
      };

      Vue.createApp({
        data() {
          return {
            active: "Home",
          };
        },
        components: {
          Home,
          Classify,
          Cart,
          Mine,
        },
      }).mount("#app");
    </script>
  </body>
</html>
